﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Windstamp.Utility.BookDownload.Common;
using Windstamp.Utility.BookDownload.Entity;

namespace Windstamp.Utility.BookDownload.Core {
    /// <summary>
    /// 下载入口处
    /// </summary>
    public class DownloadEntrance {
        /// <summary>
        /// 主页面的实体
        /// </summary>
        public MainPageInfo Info { get; private set; }

        MainPage page;

        /// <summary>
        /// 解析页面
        /// </summary>
        /// <param name="urlPage">咨询收到的 Url</param>
        public void AnalyzePage(string urlPage) {
            page = new MainPage(urlPage);

            page.AnalyzeMainPage();
            Info = page.Info;
        }

        /// <summary>
        /// 下载当前页面的正文图片
        /// </summary>
        public void StartDownloadMain() {
            int result = page.Download(PageType.Text);
            DownloadCompleteStatus(result, string.Format("{0}页-{1}页下载完成。", Info.BeginPageNum, Info.EndPageNum));
        }

        /// <summary>
        /// 下载当前页面的附属页
        /// </summary>
        public void StartAffiliatedDownload() {
            if(!string.IsNullOrEmpty(Info.ImgOriginalUrlTemp)) {
                PageType[] types = {
                                        PageType.Cover,
                                        PageType.Title,
                                        PageType.Copyright,
                                        PageType.Preface,
                                        PageType.Index
                                   };
                bool okFinished = true;
                int result;
                for(int i = 0; i < types.Length; i++) {
                    result = page.Download(types[i]);
                    if(result != 0) {
                        okFinished = false;
                        DownloadCompleteStatus(result, "");
                        return;
                    }
                }
                if(okFinished) {
                    DownloadCompleteStatus(0, "附属页下载完成。");
                }
            }
        }

        /// <summary>
        /// 下载完成情况
        /// </summary>
        /// <param name="result">下载完成后的状态号</param>
        /// <param name="okMsg">成功完成后的消息</param>
        private void DownloadCompleteStatus(int result, string okMsg) {
            switch(result) {
                case 0:
                    PromptHelper.Handlers["StatusStripMsg"](okMsg, PromptType.Information);
                    break;
                case 1:
                    throw new Exception("antispiderShowVerify");
                case 2:
                    throw new Exception("notGetUrl");
                case 3:
                    throw new Exception("stopedByOther");
                case 403:
                    throw new Exception("403");
            }
        }

        /// <summary>
        /// 停止
        /// </summary>
        public void Stop() {
            page.Stop();
        }
    }
}
